﻿using System;
using System.Reflection.Emit;
using msilgc.cbuilder.CSyntaxTree;
using msilgc.cbuilder.MSILSyntaxTree;
using msilgc.CSyntaxTree;

namespace msilgc.cbuilder.CBuilder
{
    internal class ReturnTranslator : ITranslator {
        public ICStatement TranslateAndAdd(CMethodBody methodBody, CBasicBlock currentBlock, BasicBlock block, Instruction instruction) {
            if(instruction.Inst != OpCodes.Ret) {
                throw new Exception("unexpected instruction: " + instruction); 
            }
            ICStatement statement;
            if(EvaluationStackHelper.CurrentEvaluationStackSize(currentBlock) == 0) {
                statement = new ReturnStatement();
            } else {
                IVariable retVariable = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
                statement = new ReturnStatement(retVariable);
            }
            currentBlock.Statements.Add(statement);
            return statement;
        }
    }
}